package com.example.demo.service.impl;

import com.baomidou.mybatisplus.extension.api.IErrorCode;
import com.baomidou.mybatisplus.extension.api.R;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.demo.entity.Order;
import com.example.demo.entity.OrderDetail;
import com.example.demo.entity.vo.OrderVO;
import com.example.demo.mapper.OrderMapper;
import com.example.demo.service.OrderDetailService;
import com.example.demo.service.OrderService;
import com.example.demo.service.StorageService;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

/**
 * <p>
 * 订单主表 服务实现类
 * </p>
 *
 * @author ElonChung
 * @since 2020-05-12
 */
@Log4j2
@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements OrderService {

    @Resource
    OrderDetailService orderDetailService;

    @Resource
    StorageService storageService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public R addOrder(OrderVO orderVO) {
        Order order = new Order();
        BeanUtils.copyProperties(orderVO, order);
        try {
            //下单
            log.info("开始下单=====>");
            if (this.save(order)) {
                // 子单数据录入
                List<OrderDetail> orderDetailList = orderVO.getDetailList();
                if (orderDetailList.size() > 0) {
                    orderDetailList.forEach(detail -> {
                        log.info("开始下子单=====>");
                        orderDetailService.save(detail);
                        //减库存冻结
                        log.info("减库存冻结=====>");

                        storageService.reduceStorage(detail.getGoodsId(), detail.getCount());
                    });
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            return R.failed(e.getMessage());
        }
        return R.ok(order);
    }
}
